/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/// <reference path="../base/lcc.ts" />
/// <reference path="../base/loading-module.ts" />
/// <reference path="../base/variable.ts" />
/// <reference path="../base/reference.ts" />
/// <reference path="../utils/js.ts" />

namespace lcc {

const TAG = "lcc/pack/pack-manager.ts";

/**
 * @zh
 * 真实文件路径
 */
export interface RealFilePath {
	/**
	 * @zh
	 * 真实路径
	 */
	rpath:string;

	/**
	 * @zh
	 * 资源包
	 */
	bundle?:__cc__.AssetManager.Bundle;
}

/**
 * @zh
 * 包管理器
 */
export class PackManager extends LoadingModule {
	/**
	 * @zh
	 * 管理器实例
	 */
	private static _instance:PackManager;

	/**
	 * @zh
	 * 获得单例对象
	 */
	public static getInstance() : PackManager  {
		if(!PackManager._instance){
			PackManager._instance = new PackManager();
		}
		return PackManager._instance;
	}

	/**
	 * @zh
	 * 包映射表
	 */
	private _packs:{[key:string]:PackLoader} = utils.js.createMap();

	/**
	 * @zh
	 * 获得指定包
	 * 
	 * @param name - 包名称
	 */
	public getPack(name:string){
		return this._packs[name];
	}
	
	/**
	 * @zh
	 * 加载包
	 * 
	 * @param name - 包名称
	 * @param url - 包URL路径
	 */
	public async loadPack(name:string, url?:string){
		let pack = this._packs[name];
		if(!pack){
			this.setLoading(true);
			setVariable("pack", name);
			this.emit("loadbegin", name);
			let bundle = await utils.asset.loadBundle(url || name);
			let PackLoaderType = getRef<typeof PackLoader>(`${name}://PackLoader`) || PackLoader;
			let packLoader = new PackLoaderType(name, bundle);
			this._packs[name] = packLoader;
			await indexMgr.loadPackIndexes(bundle, name);
			await packLoader.onLoad();
			this.emit("loadend", name);
			this.setLoading(false);
		}
		return pack;
	}

	/**
	 * @zh
	 * 释放包
	 * 
	 * @param name - 包名称
	 */
	public releasePack(name:string){
		let pack = this._packs[name];
		if(pack){
			let bundle = pack.getBundle();
			this.emit("releasebegin", name);
			pack.onDestroy();
			indexMgr.removePackIndexes(bundle, name);
			delete this._packs[name];
			clearRefs(new RegExp(`^${name}://.*$`));
			__cc__.assetManager.removeBundle(bundle);
			this.emit("releaseend", name);
		}
	}
	
	/**
	 * @zh
	 * 解析文件路径
	 * 
	 * @param path - 文件路径
	 */
	public parseFilePath(path:string):RealFilePath{
		if(path.indexOf("://") == -1){
			return { rpath : path };
		}else{
			let parts = path.split("://");
			return {
				rpath : parts[1],
				bundle : this.getPack(parts[0]).getBundle(),
			};
		}
	}
}

/**
 * @zh
 * 包管理器对象
 */
export const packMgr = PackManager.getInstance();

}
